package com.slipper.system.codeless.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slipper.system.codeless.bo.InterfaceBO;
import com.slipper.system.codeless.dao.InterfaceDao;
import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@ReadTransactional
public class InterfaceService {
    @Resource
    private InterfaceDao interfaceDao;
    
    public InterfaceBO queryBy(String id) {
        return interfaceDao.queryBy(id);
    }
    
    public List<InterfaceBO> queryList(InterfaceBO bo) {
        return interfaceDao.queryList(bo);
    }

    public List<InterfaceBO> queryList(String[] ids) {
        return interfaceDao.queryListByIds(ids);
    }
    
    public PageInfo<InterfaceBO> queryPage(InterfaceBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(interfaceDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(InterfaceBO bo) {
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            return interfaceDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            return interfaceDao.insert(bo);
        }
    }

    @WriteTransactional
    public void saveList(List<InterfaceBO> interfaceList) {
        if (interfaceList == null) return;

        interfaceList.forEach(interfaceBO -> {
            if (interfaceDao.queryBy(interfaceBO.getId()) != null) {
                interfaceDao.update(interfaceBO);
            } else {
                interfaceBO.setUpdateTime(System.currentTimeMillis());
                interfaceBO.setCreateTime(System.currentTimeMillis());
                interfaceDao.insert(interfaceBO);
            }
        });
    }

    @WriteTransactional
    public int delete(InterfaceBO bo) {
        return interfaceDao.delete(bo);
    }

    public long queryTotal(InterfaceBO bo) {
        PageHelper.startPage(0, 0);
        return new PageInfo<>(interfaceDao.queryList(bo)).getTotal();
    }

    public InterfaceBO queryByPath(String path) {
        List<InterfaceBO> interfaceList = interfaceDao.queryByPath(path);
        return interfaceList.isEmpty() ? null : interfaceList.getFirst();
    }

    public boolean existsPath(String id, String path) {
        return interfaceDao.existsPath(id, path) > 0;
    }
}
